#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h> 
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>

#define SERVER_PORT 8080
#define BUFFER_SIZE 64

int main()
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket error");
        exit(-1);
    }
    printf("sockfd is %d\n", sockfd);

    /* 设置端口复用:一定要写在bind之前 */
    int optVal = 1;
    int ret;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optVal, sizeof(optVal));
    if (ret == -1)
    {
        perror("setsockopt error");
        exit(-1);
    }

    struct sockaddr_in localAddress;
    /* 所有的结构体定义都要清楚脏数据 */
    memset(&localAddress, 0, sizeof(localAddress));

    localAddress.sin_family = AF_INET;          // ipv
    localAddress.sin_port = htons(SERVER_PORT);
    localAddress.sin_addr.s_addr = INADDR_ANY;

    socklen_t localAddressLength = sizeof(localAddress);

    /* 绑定本地IP */
    ret = bind(sockfd, (const struct sockaddr *)&localAddress, localAddressLength);
    if (ret == -1)
    {
        perror("bind error");
        exit(-1);
    }

    /* 监听套接字 */
    ret = listen(sockfd, BUFFER_SIZE);
    if (ret == -1)
    {
        perror("listen error");
        exit(-1);
    }

    struct sockaddr_in clientAddress;
    memset(&clientAddress, 0, sizeof(clientAddress));
    socklen_t clientAddressLength = 0;

    /* accept的返回值是和 【客户端通信】的文件描述符 */
    int connfd = accept(sockfd, (struct sockaddr *)&clientAddress, &clientAddressLength);
    if (connfd == -1)
    {
        perror("accept error");
        exit(-1);
    }
    printf("connfd:%d\n", connfd);


    /* 服务器一直等待接收客户端的信息，并作出反馈 */
    /* 服务器365天 24小时 不宕机 */
    char readBuffer[BUFFER_SIZE] = { 0 };
    int readBytes = 0;

    char writeBuffer[BUFFER_SIZE] = { 0 };
    int writeBytes = 0;
    while (1)
    {
        readBytes = read(connfd, readBuffer, BUFFER_SIZE - 1);
        if (readBytes < 0)
        {
            perror("read error");
        }
        else if (readBytes == 0)
        {
            /* 这边读到的字节数为0， 说明什么？ */
            printf("客户端下线\n");
            break;
        }
        else
        {
            printf("readBytes:%d,\treadBuffer:%s\n", readBytes, readBuffer);
            for (int idx = 0; idx < readBytes; idx++)
            {
                /* 转大写 */
                writeBuffer[idx] = toupper(readBuffer[idx]);
            }

            /* 写回客户端 */
            write(connfd, writeBuffer, readBytes);
        }
    }
    

    /* 回收资源一定要有 */
    close(sockfd);
    close(connfd);
    return 0;
}
